package com.sun.service.impl;

import cn.hutool.core.util.IdUtil;
import com.sun.config.FTPPoolConfig;
import com.sun.enumstatus.UploadStatus;
import com.sun.mapper.FileMapper;
import com.sun.pojo.File;
import com.sun.service.FtpService;
import com.sun.util.FtpContinueClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author lk
 */
@Service
@Slf4j
public class FtpServiceImpl implements FtpService {

    @Autowired
    private FtpContinueClient ftpContinueClient;
    @Autowired
    private FTPPoolConfig ftpPoolConfig;
    @Autowired
    private FileMapper fileMapper;

    @Override
    public String upload(String orginName)  {
        try {
            boolean connect = ftpContinueClient.connect(ftpPoolConfig.getHost(), ftpPoolConfig.getPort(), ftpPoolConfig.getUsername(), ftpPoolConfig.getPassword());
            log.info("ftp连接成功:{}",connect);
            String localhostPath = ftpPoolConfig.getLocalhostPath();
            String remotePath = ftpPoolConfig.getWorkingDirectory();
            String localPathName=localhostPath+orginName;
            String uuid = IdUtil.randomUUID();
            String type=orginName.substring(orginName.lastIndexOf(".")+1);
            String remotePathName=remotePath+uuid+orginName.substring(orginName.lastIndexOf("."));
            String ftpRemotePathName="/home/sinog2c"+remotePathName;
            //将之前查询出来的文件变成状态变为-1
            fileMapper.changeFileStatus(orginName);
            File file=new File();
            //上传保留一份至数据库中
            file.setName(orginName);
            file.setType(type);
            file.setPath(ftpRemotePathName);
            file.setCreateTime(new Date());
            int i = fileMapper.saveFile(file);
            if(i>0){
                UploadStatus upload = ftpContinueClient.upload(localPathName,remotePathName);
                log.info("文件上传状态:{}",upload);
                return upload.getMessage();
            }else{
                return "上传失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                ftpContinueClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "失败";
    }

    @Override
    public List<File> findAll() {
        return fileMapper.selectAll();
    }

    @Override
    public String downloadByName(String name) {
        String ftpPath = fileMapper.findFileByName(name);
        try {
            ftpContinueClient.download(ftpPath,name);
        } catch (IOException e) {
            e.printStackTrace();
            return "下载失败";
        }
        return "下载成功";
    }
}
